package com.petmall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.petmall.cart.feign.ProduceFeignService;
import com.petmall.cart.interceptor.CartInterceptor;
import com.petmall.cart.service.CartService;
import com.petmall.cart.vo.CartItemVo;
import com.petmall.cart.vo.CartVo;
import com.petmall.cart.vo.SkuInfoVo;
import com.qianji.common.constant.CartConstant;
import com.qianji.common.to.UserInfoTo;
import com.qianji.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author liang zai
 * @date 2022/4/15 15:00
 * @description
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProduceFeignService produceFeignService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = cartOps();
        String user = (String) cartOps.get(skuId.toString());
        //判断用户购物车是否有该sku项
        if (StringUtils.isEmpty(user)){
            CartItemVo itemVo = new CartItemVo();
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                //查询sku的相关信息
                R info = produceFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfoVo = info.getData("skuInfo", new TypeReference<SkuInfoVo>() {});
                itemVo.setTitle(skuInfoVo.getSkuTitle());
                itemVo.setImage(skuInfoVo.getSkuDefaultImg());
                itemVo.setCheck(true);
                itemVo.setCount(num);
                itemVo.setPrice(skuInfoVo.getPrice());
                itemVo.setSkuId(skuId);
            }, threadPoolExecutor);

            CompletableFuture<Void> skuAttr = CompletableFuture.runAsync(() -> {
                //远程调用，获取sku的组合销售属性
                List<String> skuSaleAttrValues = produceFeignService.getSkuSaleAttrValues(skuId);
                itemVo.setSkuAttrValues(skuSaleAttrValues);
            }, threadPoolExecutor);

            //等待执行完成
            CompletableFuture.allOf(future,skuAttr).get();

            //sku放入到用户购物车的redis中
            cartOps.put(skuId.toString(),JSON.toJSONString(itemVo));
            return itemVo;
        }else {
            //说明购物车已经有了该购物项 购物车+1
            CartItemVo cartItemVo = JSON.parseObject(user, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
    }

    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = cartOps();
        String s = (String) cartOps.get(skuId.toString());
        CartItemVo cartItemVo = JSON.parseObject(s, CartItemVo.class);
        return cartItemVo;
    }

    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cartVo = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.THREAD_LOCAL.get();
        if (userInfoTo.getUserId()!=null){
            //登录的用户
            //获取redis购物车的数据
            BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(userInfoTo.getUserId().toString());
            BoundHashOperations<String, Object, Object> cartOps = cartOps();
            //登录用户的购物车信息
            String userId = CartConstant.CART_USER_NAME + userInfoTo.getUserId();
            //临时用户的购物车信息
            String userKey = CartConstant.CART_USER_NAME + userInfoTo.getUserKey();
            //如果临时购物车还没有合并，进行合并
            List<CartItemVo> cartItems = getCartItems(userKey);

            HashMap<String, CartItemVo> map = new HashMap<>();

            if (cartItems!=null && cartItems.size()>0){
                //临时购物车还有数据，需要和登录的用户购物车合并数据
                for (CartItemVo item:cartItems) {
                    cartOps.put(item.getSkuId().toString(),JSON.toJSONString(item));
                }
                //添加完成后清除临时购物车的数据
                redisTemplate.delete(userKey);
            }
            List<CartItemVo> cartItem = getCartItems(userId);
            cartVo.setItems(cartItem);
        }else {
            //临时用户
            //临时用户的购物车信息
            String userKey = CartConstant.CART_USER_NAME + userInfoTo.getUserKey();
            List<CartItemVo> cartItems = getCartItems(userKey);
            cartVo.setItems(cartItems);
        }
        return cartVo;
    }

    /**
     * 远程调用：订单服务调用【更新最新价格】
     * 获取当前用户购物车所有选中的商品项check=true【从redis中取】
     */
    @Override
    public List<CartItemVo> getCheckItems() throws ExecutionException, InterruptedException {
        UserInfoTo userInfoTo = CartInterceptor.THREAD_LOCAL.get();
        List<CartItemVo> cartItemVos = new ArrayList<>();
        Long userId = userInfoTo.getUserId();
        if (userInfoTo!=null){
            if (userId!=null){
                //登录的用户 获取购物车数据
                CartVo cart = getCart();
                //获取所有的购物车
                List<CartItemVo> items = cart.getItems();
                //过滤掉所有没勾选的商品
                cartItemVos = items.stream().filter(CartItemVo::getCheck).collect(Collectors.toList());

            }else {
                //未登录的用户 返回null
                return null;
            }
        }
        return cartItemVos;
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = cartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = cartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = cartOps();
        CartItemVo cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    private List<CartItemVo> getCartItems(String userKey) {
        //获取购物车的所有商品
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(userKey);
        //可以获取到购物车的数据
        List<Object> values = operations.values();
        if (values!=null && values.size()>0){
            List<CartItemVo> collect = values.stream().map((item) -> {
                //封装成实体类
                CartItemVo cartItemVo = JSON.parseObject((String) item, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    //获取用户是临时用户还是登录用户信息，并封装到redis
    private BoundHashOperations<String, Object, Object> cartOps() {
        //查看用户是离线的临时用户还是登录用户
        UserInfoTo userInfoTo = CartInterceptor.THREAD_LOCAL.get();
        String cartKey = "";
        if (userInfoTo.getUserId() != null){
            //登录的用户
            Long userId = userInfoTo.getUserId();
            cartKey =  CartConstant.CART_USER_NAME + userId;
        }else {
            //临时用户
            String userKey = userInfoTo.getUserKey();
            cartKey = CartConstant.CART_USER_NAME + userKey;
        }
        //绑定这个key，以后所有的操作都是针对这个key
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(cartKey);
        return boundHashOps;
    }
}
